package com.sbl.bajw.pc.service;

import java.awt.image.BufferedImage;

import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Service;

import com.sbl.bajw.common.JCaptchaServiceSingleton;
import com.sbl.bajw.common.web.WebContext;

@Service
public class JcaptchaService {

	public final String CORRECT = "CORRECT";
	public final String ERROR = "ERROR";
	public final String EXPIRE = "EXPIRE";

	public static final String CAPTCHA_IMAGE_FORMAT = "jpeg";

	public BufferedImage getImage() throws Exception {

		HttpServletRequest request = WebContext.getRequest();

		String captchaId = request.getSession().getId();
		BufferedImage challenge = JCaptchaServiceSingleton.getInstance()
				.getImageChallengeForID(captchaId, request.getLocale());

		return challenge;
	}

	public String Check(String Jcaptcha) {
		HttpServletRequest requset = WebContext.getRequest();
		String sessionId = requset.getSession().getId();
		boolean flag = false;
		try {
			flag = JCaptchaServiceSingleton.getInstance()
					.validateResponseForID(sessionId, Jcaptcha);
		} catch (Exception e) {
			return EXPIRE;
		}

		if (flag) {
			return CORRECT;
		} else {
			return ERROR;
		}
	}
}
